<template>
  <div class="rule-management-optimized">
    <!-- 搜索过滤栏 - 只保留搜索框 -->
    <el-card class="search-filter-card">
      <div class="search-filter-bar">
        <div class="search-group">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索节点名称、操作名称..."
            clearable
            @input="handleSearch"
            style="width: 300px"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>

        <div class="action-group">
          <el-button @click="expandAll" :icon="Expand">展开全部</el-button>
          <el-button @click="collapseAll" :icon="Fold">折叠全部</el-button>
          <el-button @click="getRootNodes" :icon="Refresh">刷新</el-button>
          <el-button type="primary" @click="handleAdd">添加顶级菜单</el-button>
          <el-dropdown @command="handleBatchAction" :disabled="selectedRows.length === 0">
            <el-button type="success" :icon="MoreFilled">
              批量操作
              <el-icon class="el-icon--right"><ArrowDown /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="enable" :disabled="selectedRows.length === 0">
                  批量启用 ({{ selectedRows.length }})
                </el-dropdown-item>
                <el-dropdown-item command="disable" :disabled="selectedRows.length === 0">
                  批量禁用 ({{ selectedRows.length }})
                </el-dropdown-item>
                <el-dropdown-item command="delete" divided :disabled="selectedRows.length === 0">
                  批量删除 ({{ selectedRows.length }})
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
    </el-card>

    <!-- 统计卡片 - 优化：固定高度，避免CLS -->
    <div class="stats-container">
      <div class="stats-cards">
        <el-card
          v-for="stat in statsData"
          :key="stat.label"
          class="stat-card"
          :body-style="{ height: '80px', padding: '20px' }"
          v-loading="loading && (!statsData || statsData.length === 0)"
          element-loading-text="加载中..."
          element-loading-background="rgba(255, 255, 255, 0.8)"
        >
          <div v-if="!loading || (statsData && statsData.length > 0)" class="stat-content">
            <div class="stat-icon" :style="{ backgroundColor: stat.color }">
              <el-icon><component :is="stat.icon" /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stat.value }}</div>
              <div class="stat-label">{{ stat.label }}</div>
            </div>
          </div>
          <!-- 骨架屏占位 -->
          <div v-else class="stat-skeleton">
            <div class="skeleton-icon"></div>
            <div class="skeleton-text">
              <div class="skeleton-value"></div>
              <div class="skeleton-label"></div>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 树形表格 - 优化：添加最小高度和过渡动画 -->
    <el-card class="table-card">
      <div class="table-container">
        <el-table
          ref="tableRef"
          :data="filteredData"
          row-key="id"
          v-loading="loading"
          element-loading-text="加载中..."
          element-loading-background="rgba(255, 255, 255, 0.9)"
          @selection-change="handleSelectionChange"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          :row-class-name="getRowClassName"
          :cell-class-name="getCellClassName"
          lazy
          :load="loadChildNodes"
          stripe
          border
          :header-cell-style="{ background: '#fafafa', fontWeight: 'bold' }"
          :row-style="{ transition: 'all 0.3s ease' }"
          :default-expand-all="false"
          :expand-row-keys="[]"
          class="rule-tree-table"
        >
          <!-- 多选列 -->
          <el-table-column type="selection" width="55" :reserve-selection="true" />

          <!-- 层级指示器 + 节点信息列 -->
          <el-table-column prop="title" label="节点名称" min-width="280">
            <template #default="{ row }">
              <div class="node-cell" :style="{ paddingLeft: `${row._level * 20 + 10}px` }">
                <!-- 层级图标 -->
                <div class="level-icon" :class="`level-icon-${row._level}`">
                  <el-icon v-if="row._level === 0"><FolderOpened /></el-icon>
                  <el-icon v-else-if="row._level === 1"><Folder /></el-icon>
                  <el-icon v-else-if="row._level === 2"><Document /></el-icon>
                  <el-icon v-else-if="row._level >= 3"><Link /></el-icon>
                </div>

                <!-- 节点信息 -->
                <div class="node-info">
                  <div class="node-title">
                    <span>{{ row.title }}</span>
                    <el-tag v-if="row.menu === 1" size="small" type="info" effect="plain">
                      菜单
                    </el-tag>
                  </div>
                  <div class="node-subtitle">{{ row.name || '未设置操作名' }}</div>
                </div>
              </div>
            </template>
          </el-table-column>

          <!-- 父ID列 -->
          <el-table-column prop="pid" label="父ID" width="100" />

          <!-- 模块列 - 优化：使用浅色背景，深色文字，提高对比度 -->
          <el-table-column prop="module" label="所属模块" width="120">
            <template #default="{ row }">
              <el-tag
                :style="{
                  backgroundColor: getModuleColor(row.module) + '20',
                  borderColor: getModuleColor(row.module),
                  color: getModuleColor(row.module),
                }"
                effect="plain"
              >
                {{ row.module }}
              </el-tag>
            </template>
          </el-table-column>

          <!-- URL列 - 修复：显示mig_src字段 -->
          <el-table-column label="URL地址" min-width="180" show-overflow-tooltip>
            <template #default="{ row }">
              <span v-if="row.mig_src" class="url-text">{{ row.mig_src }}</span>
              <span v-else class="no-url">-</span>
            </template>
          </el-table-column>

          <!-- 操作名称列 -->
          <el-table-column prop="name" label="操作名称" min-width="150" show-overflow-tooltip />

          <!-- 是否菜单列 -->
          <el-table-column prop="menu" label="是否菜单" width="100">
            <template #default="{ row }">
              <span v-if="row.menu === 1" class="green">是</span>
              <span v-else class="red">否</span>
            </template>
          </el-table-column>

          <!-- 状态列 -->
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="{ row }">
              <el-switch
                v-model="row.status"
                :active-value="1"
                :inactive-value="0"
                @change="(val: number) => handleStatusChange(row, val)"
              />
            </template>
          </el-table-column>

          <!-- 操作列 -->
          <el-table-column label="操作" width="220" fixed="right" align="center">
            <template #default="{ row }">
              <el-button-group class="operation-group">
                <el-tooltip content="查看详情" placement="top">
                  <el-button size="small" @click="handleView(row)" :icon="View" />
                </el-tooltip>
                <el-tooltip content="添加子节点" placement="top">
                  <el-button size="small" @click="handleAddChild(row)" :icon="Plus" />
                </el-tooltip>
                <el-tooltip content="编辑" placement="top">
                  <el-button size="small" @click="handleEdit(row)" :icon="Edit" />
                </el-tooltip>
                <el-tooltip content="删除" placement="top">
                  <el-button size="small" @click="handleDelete(row)" :icon="Delete" />
                </el-tooltip>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>

        <!-- 骨架屏行 - 优化CLS：避免布局跳动 -->
        <div v-if="loading && (!filteredData || filteredData.length === 0)" class="skeleton-rows">
          <div v-for="i in 5" :key="i" class="skeleton-row">
            <div class="skeleton-cell">
              <div class="skeleton-bar" style="width: 80%; height: 16px"></div>
            </div>
            <div class="skeleton-cell">
              <div class="skeleton-bar" style="width: 60px; height: 16px"></div>
            </div>
            <div class="skeleton-cell">
              <div class="skeleton-bar" style="width: 80px; height: 16px"></div>
            </div>
            <div class="skeleton-cell">
              <div class="skeleton-bar" style="width: 120px; height: 16px"></div>
            </div>
            <div class="skeleton-cell">
              <div class="skeleton-bar" style="width: 100px; height: 16px"></div>
            </div>
            <div class="skeleton-cell">
              <div class="skeleton-bar" style="width: 60px; height: 16px"></div>
            </div>
            <div class="skeleton-cell">
              <div class="skeleton-bar" style="width: 60px; height: 16px"></div>
            </div>
            <div class="skeleton-cell">
              <div class="skeleton-bar" style="width: 160px; height: 16px"></div>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-if="!loading && (!filteredData || filteredData.length === 0)" class="empty-state">
          <el-empty description="暂无数据" :image-size="100" />
        </div>
      </div>
    </el-card>

    <!-- 快捷操作面板 -->
    <el-card class="quick-actions-card" v-if="recentActions.length > 0">
      <template #header>
        <span>最近操作</span>
      </template>
      <div class="recent-actions">
        <el-tag
          v-for="action in recentActions"
          :key="action.id"
          type="info"
          effect="plain"
          class="action-tag"
          @click="handleActionClick(action)"
        >
          {{ action.text }}
        </el-tag>
      </div>
    </el-card>

    <!-- 添加/编辑规则抽屉 -->
    <el-drawer
      v-model="drawerVisible"
      :title="drawerTitle"
      size="600px"
      direction="rtl"
      @close="handleDrawerClose"
    >
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="ruleRules"
        label-width="120px"
        style="padding: 20px"
      >
        <el-form-item label="父级菜单/节点" prop="pid">
          <el-select
            v-model="ruleForm.pid"
            placeholder="请选择父级菜单/节点"
            @change="handleParentChange"
          >
            <el-option value="0" label="作为顶级菜单/节点" />
            <el-option
              v-for="item in parentOptions"
              :key="item.id"
              :label="item.titleWithLevel"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="所属模块" prop="module">
          <el-select v-model="ruleForm.module" placeholder="请选择模块">
            <el-option
              v-for="item in moduleOptions"
              :key="item.name"
              :label="item.title"
              :value="item.name"
            />
          </el-select>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="节点名称" prop="title">
              <el-input v-model="ruleForm.title" placeholder="请输入节点名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="操作名称" prop="name">
              <el-input v-model="ruleForm.name" placeholder="请输入操作名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="URL地址">
          <el-input v-model="ruleForm.src" placeholder="请输入URL地址" />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="菜单图标">
              <el-input v-model="ruleForm.icon" placeholder="请输入图标类名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序">
              <el-input-number v-model="ruleForm.sort" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="是否菜单">
          <el-switch v-model="ruleForm.menu" :active-value="1" :inactive-value="0" />
        </el-form-item>

        <el-form-item label="左侧菜单显示">
          <el-radio-group v-model="ruleForm.showLeftMenu">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">不是</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="状态">
          <el-radio-group v-model="ruleForm.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div class="drawer-footer">
        <el-button @click="drawerVisible = false">取消</el-button>
        <el-button type="primary" @click="submitRule">确定</el-button>
      </div>
    </el-drawer>

    <!-- 查看规则详情抽屉 -->
    <el-drawer v-model="viewDrawerVisible" title="查看规则详情" size="400px" direction="rtl">
      <div v-if="currentViewRow" class="view-detail-container">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="ID号">{{ currentViewRow.id }}</el-descriptions-item>
          <el-descriptions-item label="菜单/节点名称">
            {{ currentViewRow.title }}
          </el-descriptions-item>
          <el-descriptions-item label="父ID">{{ currentViewRow.pid }}</el-descriptions-item>
          <el-descriptions-item label="所属模块">{{ currentViewRow.module }}</el-descriptions-item>
          <el-descriptions-item label="URL链接">
            {{ currentViewRow.mig_src || currentViewRow.src || '无' }}
          </el-descriptions-item>
          <el-descriptions-item label="是否是菜单">
            {{ currentViewRow.menu === 1 ? '是' : '否' }}
          </el-descriptions-item>
          <el-descriptions-item label="操作日志名称">
            {{ currentViewRow.name || '无' }}
          </el-descriptions-item>
          <el-descriptions-item label="排序">{{ currentViewRow.sort }}</el-descriptions-item>
          <el-descriptions-item label="菜单图标">
            {{ currentViewRow.icon || '无' }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="currentViewRow.status === 1 ? 'success' : 'danger'">
              {{ currentViewRow.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, onMounted, computed, nextTick } from 'vue'
  import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
  import {
    Search,
    Expand,
    Fold,
    Refresh,
    MoreFilled,
    View,
    Plus,
    Edit,
    Delete,
    Grid,
    FolderOpened,
    Folder,
    Document,
    Link,
    ArrowDown,
    CircleCheck,
    CircleClose,
  } from '@element-plus/icons-vue'
  import { getRuleList, saveRule, deleteRule, rule } from '@/api/home/rule'

  // 类型定义
  interface RuleItem {
    id: number
    pid: number
    module: string
    title: string
    name: string
    src: string
    mig_src?: string // URL地址字段
    status: number
    condition: string
    listorder: number
    desc: string
    sort: number
    menu: number
    icon: string
    children?: RuleItem[]
    hasChildren?: boolean
    _level?: number
    showLeftMenu?: number
    [key: string]: any
  }

  // 数据相关
  const ruleList = ref<RuleItem[]>([])
  const loading = ref(false)
  const nodeLoadingMap = ref<{ [key: number]: boolean }>({})
  const searchKeyword = ref('')
  const selectedRows = ref<RuleItem[]>([])
  const recentActions = ref<Array<{ id: number; text: string }>>([])

  // 表格引用
  const tableRef = ref()

  // 抽屉相关
  const drawerVisible = ref(false)
  const viewDrawerVisible = ref(false)
  const drawerTitle = ref('')
  const isEdit = ref(false)
  const currentViewRow = ref<any>(null)

  // 表单数据
  const ruleForm = reactive({
    id: 0,
    pid: 0,
    module: '',
    title: '',
    name: '',
    src: '',
    status: 1,
    condition: '',
    listorder: 0,
    desc: '',
    sort: 0,
    menu: 1,
    icon: '',
    showLeftMenu: 1,
  })

  // 表单验证规则
  const ruleRules = {
    title: [{ required: true, message: '请输入权限名称', trigger: 'blur' }],
    name: [{ required: true, message: '请输入权限标识', trigger: 'blur' }],
  }

  // 表单引用
  const ruleFormRef = ref()

  // 所有节点选项数据
  const parentOptions = ref<{ id: number; titleWithLevel: string }[]>([])

  // 模块选项数据
  const moduleOptions = ref<{ name: string; title: string }[]>([])

  // 获取所有节点（递归）
  const getAllNodes = (nodes: RuleItem[]): RuleItem[] => {
    // 递归获取节点数据
    const result: RuleItem[] = []
    const traverse = (nodeList: RuleItem[]) => {
      // 当前层级节点数量统计
      nodeList.forEach(node => {
        // 添加节点处理
        result.push(node)
        if (node.children) {
          // 递归处理子节点
          traverse(node.children)
        }
      })
    }
    traverse(nodes)
    // 递归完成统计
    return result
  }

  // 统计缓存
  const statsCache = ref<{ data: any[]; timestamp: number } | null>(null)
  const CACHE_DURATION = 5000 // 5秒缓存
  const statsLoading = ref(false) // 添加统计加载状态

  // 优化：添加默认统计数据显示，避免初始为0
  const defaultStatsData = [
    { label: '总节点', value: 0, color: '#1677ff', icon: 'Grid' },
    { label: '顶级节点', value: 0, color: '#52c41a', icon: 'FolderOpened' },
    { label: '启用节点', value: 0, color: '#52c41a', icon: 'CircleCheck' },
    { label: '禁用节点', value: 0, color: '#f5222d', icon: 'CircleClose' },
  ]

  // 统计卡片数据 - 使用独立API获取，避免加载所有数据
  const statsData = computed(() => {
    const now = Date.now()

    // 检查缓存是否有效
    if (statsCache.value && now - statsCache.value.timestamp < CACHE_DURATION) {
      // 使用缓存统计数据
      return statsCache.value.data
    }

    // 如果缓存无效，返回默认值，避免显示为0
    return defaultStatsData
  })

  // 获取统计数据 - 优化：使用独立API
  const fetchStatsData = async () => {
    try {
      statsLoading.value = true
      // 获取统计数据处理

      const response: any = await rule.getStats()

      if (response && response.data) {
        const result = [
          { label: '总节点', value: response.data.total || 0, color: '#1677ff', icon: 'Grid' },
          {
            label: '顶级节点',
            value: response.data.top_level || 0,
            color: '#52c41a',
            icon: 'FolderOpened',
          },
          {
            label: '启用节点',
            value: response.data.enabled || 0,
            color: '#52c41a',
            icon: 'CircleCheck',
          },
          {
            label: '禁用节点',
            value: response.data.disabled || 0,
            color: '#f5222d',
            icon: 'CircleClose',
          },
        ]

        console.log('获取统计数据成功:', result)

        // 更新缓存
        statsCache.value = {
          data: result,
          timestamp: Date.now(),
        }
      }
    } catch (error) {
      console.error('获取统计数据失败:', error)
    } finally {
      statsLoading.value = false
    }
  }

  // 过滤后的数据 - 只根据搜索关键词过滤
  const filteredData = computed(() => {
    if (!searchKeyword.value) {
      return ruleList.value
    }

    const keyword = searchKeyword.value.toLowerCase()

    const filter = (nodes: RuleItem[]): RuleItem[] => {
      return nodes
        .filter(node => {
          const matchKeyword =
            node.title.toLowerCase().includes(keyword) ||
            node.name.toLowerCase().includes(keyword) ||
            node.mig_src?.toLowerCase().includes(keyword) ||
            node.module?.toLowerCase().includes(keyword)

          const filteredChildren = node.children ? filter(node.children) : []

          return matchKeyword || (node.children && filteredChildren.length > 0)
        })
        .map(node => ({
          ...node,
          children: node.children ? filter(node.children) : [],
        }))
    }

    return filter(ruleList.value)
  })

  // 搜索处理
  const handleSearch = () => {
    // 搜索逻辑通过 computed 自动过滤
  }

  // 获取所有节点数据用于下拉选择
  const loadAllNodesForDropdown = async () => {
    try {
      console.log('开始加载所有节点数据用于下拉选择')
      const response: any = await getRuleList({
        tree: true,
        withLevel: true,
        pid: 0,
      })

      if (response && response.data && Array.isArray(response.data)) {
        parentOptions.value = []
        const processNode = (nodes: any[], level: number = 0) => {
          nodes.forEach(node => {
            const indent = level > 0 ? '|--'.repeat(level) + ' ' : ''
            parentOptions.value.push({
              id: node.id,
              titleWithLevel: `${indent}${node.title}`,
            })

            if (node.children && Array.isArray(node.children) && node.children.length > 0) {
              processNode(node.children, level + 1)
            }
          })
        }

        processNode(response.data)
        console.log('加载所有节点数据完成，总数量:', parentOptions.value.length)
      } else {
        console.warn('API返回数据格式不正确或为空')
        parentOptions.value = []
      }
    } catch (error) {
      console.error('加载所有节点数据失败:', error)
      ElMessage.error('加载节点数据失败')
      parentOptions.value = []
    }
  }

  // 从模块表获取模块配置列表 - 使用专门的API
  const extractModuleOptions = async (nodes: RuleItem[]) => {
    const startTime = performance.now()

    try {
      console.log('从API获取模块列表...')
      const response: any = await rule.getModules()

      if (response && response.data && Array.isArray(response.data)) {
        // API返回的数据格式：[{ id, name, title, status, ... }]
        const modules: { name: string; title: string }[] = response.data.map((module: any) => ({
          name: module.name,
          title: module.title,
        }))

        // 按中文标题排序
        modules.sort((a, b) => a.title.localeCompare(b.title, 'zh-CN'))

        moduleOptions.value = modules
        console.log(
          '获取模块配置列表完成，总数量:',
          moduleOptions.value.length,
          '耗时:',
          performance.now() - startTime,
          'ms'
        )
      }
    } catch (error) {
      console.error('获取模块列表失败:', error)
      // 如果API失败，使用空数组
      moduleOptions.value = []
    }
  }

  // 获取根节点数据
  const getRootNodes = async () => {
    try {
      loading.value = true
      const response: any = await getRuleList({
        tree: true,
        withLevel: true,
        pid: 0,
      })

      if (response && response.data && Array.isArray(response.data)) {
        ruleList.value = response.data.map((node: any) => {
          let hasChildrenValue = false
          const hasBackendHasChildren = node.hasChildren !== undefined
          const hasChildrenData = !!node.children && node.children.length > 0

          if (hasBackendHasChildren) {
            hasChildrenValue = node.hasChildren
          } else {
            hasChildrenValue = hasChildrenData
          }

          const nodeLevel = 0

          return {
            ...node,
            _level: nodeLevel,
            hasChildren: hasChildrenValue,
            'has-children': hasChildrenValue,
          }
        })

        // 从API获取模块列表
        await extractModuleOptions(ruleList.value)

        // 优化：获取统计数据
        fetchStatsData()
      } else {
        ruleList.value = []
        // 即使没有数据，也要获取模块列表和统计数据
        await extractModuleOptions([])
        fetchStatsData()
      }
    } catch (error) {
      console.error('获取根节点数据失败:', error)
      ElMessage.error('获取节点数据失败')
      ruleList.value = []
    } finally {
      loading.value = false
    }
  }

  // 懒加载子节点
  const loadChildNodes = async (row: any, treeNode: any, resolve: any) => {
    console.log('开始加载子节点:', row)

    if (!resolve) {
      console.error('加载子节点失败: 缺少resolve函数')
      return
    }

    const parentId = row && row.id

    if (!parentId) {
      console.error('加载子节点失败: 无效的父节点ID')
      resolve([])
      return
    }

    if (nodeLoadingMap.value[parentId]) {
      console.warn('子节点已在加载中，避免重复请求')
      resolve([])
      return
    }

    nodeLoadingMap.value[parentId] = true

    let timeoutTimer: number | null = null

    try {
      if (row && row.children && Array.isArray(row.children) && row.children.length > 0) {
        console.log('使用已有的子节点数据，数量:', row.children.length)

        const parentLevel = row._level || 0
        const processedChildren = row.children.map((node: any) => ({
          ...node,
          _level: parentLevel + 1,
          hasChildren:
            node.hasChildren !== undefined
              ? node.hasChildren
              : !!node.children && node.children.length > 0,
          'has-children':
            node.hasChildren !== undefined
              ? node.hasChildren
              : !!node.children && node.children.length > 0,
        }))

        // 优化：使用nextTick确保DOM更新平滑
        await nextTick()
        resolve(processedChildren)
        nodeLoadingMap.value[parentId] = false
        console.log('使用已有数据完成加载子节点')
        return
      }

      // 优化：缩短超时时间为3秒
      const timeoutPromise = new Promise((_, reject) => {
        timeoutTimer = setTimeout(() => {
          reject(new Error('加载子节点超时'))
        }, 3000) as unknown as number
      })

      console.log('请求API获取子节点数据，父ID:', parentId)

      const response: any = await Promise.race([
        getRuleList({
          tree: true,
          withLevel: true,
          pid: parentId,
        }),
        timeoutPromise,
      ])

      console.log('API返回结果:', response)

      let childNodes: any[] = []

      if (response && response.data && Array.isArray(response.data)) {
        console.log('API返回子节点数量:', response.data.length)
        const parentLevel = row._level || 0
        childNodes = response.data.map((node: any) => {
          let hasChildrenValue = false
          const hasBackendHasChildren = node.hasChildren !== undefined
          const hasChildrenData = !!node.children && node.children.length > 0

          if (hasBackendHasChildren) {
            hasChildrenValue = node.hasChildren
          } else {
            hasChildrenValue = hasChildrenData
          }

          const childLevel = parentLevel + 1

          return {
            ...node,
            _level: childLevel,
            hasChildren: hasChildrenValue,
            'has-children': hasChildrenValue,
          }
        })
      } else {
        console.warn('API返回数据格式不正确或为空')
      }

      // 直接返回，无需延迟
      console.log('解析子节点数据，数量:', childNodes.length)

      // 优化：使用nextTick确保DOM更新平滑
      await nextTick()
      resolve(childNodes)
      nodeLoadingMap.value[parentId] = false

      console.log('子节点加载完成')
    } catch (error) {
      console.error('加载子节点失败:', error)
      ElMessage.error('加载子节点失败: ' + (error as Error).message)
      resolve([])
      nodeLoadingMap.value[parentId] = false
    } finally {
      if (timeoutTimer !== null) {
        clearTimeout(timeoutTimer)
      }
    }
  }

  // 展开全部 - 修复：递归加载所有数据
  const expandAll = async () => {
    try {
      console.log('开始展开所有节点...')

      // 递归加载所有节点数据
      const loadAllNodes = async (nodes: any[]): Promise<any[]> => {
        const result = []
        for (const node of nodes) {
          // 加载当前节点
          const fullNode = { ...node }

          // 尝试加载子节点，无论是否有hasChildren标记
          console.log('加载子节点，父ID:', fullNode.id)

          try {
            const response: any = await getRuleList({
              tree: true,
              withLevel: true,
              pid: fullNode.id,
              limit: 1000,
            })

            if (
              response &&
              response.data &&
              Array.isArray(response.data) &&
              response.data.length > 0
            ) {
              console.log('父节点', fullNode.id, '的子节点数量:', response.data.length)
              // 递归加载子节点
              const children = await loadAllNodes(response.data)
              fullNode.children = children
              fullNode.expanded = true
              fullNode.hasChildren = true
            } else {
              // 没有子节点
              fullNode.children = []
              fullNode.hasChildren = false
            }
          } catch (err) {
            console.error('加载节点', fullNode.id, '的子节点失败:', err)
            fullNode.children = []
            fullNode.hasChildren = false
          }

          result.push(fullNode)
        }
        return result
      }

      // 加载所有根节点及其子节点
      const allData = await loadAllNodes(ruleList.value)
      console.log('展开完成，总节点数:', allData.length)

      // 更新数据
      ruleList.value = allData

      // 强制刷新表格
      await nextTick()
      if (tableRef.value && tableRef.value.store) {
        // 清除缓存，确保重新渲染
        tableRef.value.store.states.lazyTreeNodeMap.value = {}
      }

      ElMessage.success('已展开所有节点')
    } catch (error) {
      console.error('展开所有节点失败:', error)
      ElMessage.error('展开失败：' + (error as Error).message)
    }
  }

  // 折叠全部
  const collapseAll = () => {
    if (tableRef.value && tableRef.value.store && tableRef.value.store.states) {
      tableRef.value.store.states.lazyTreeNodeMap.value = {}
    }
    getRootNodes()
    ElMessage.success('已折叠所有节点')
  }

  // 选中处理
  const handleSelectionChange = (selection: RuleItem[]) => {
    selectedRows.value = selection
  }

  // 批量操作
  const handleBatchAction = async (command: string) => {
    if (selectedRows.value.length === 0) {
      ElMessage.warning('请先选择要操作的节点')
      return
    }

    const selectedIds = selectedRows.value.map(row => row.id)

    try {
      if (command === 'enable') {
        await ElMessageBox.confirm(`确认启用选中的 ${selectedIds.length} 个节点吗？`)
        // 批量启用逻辑
        for (const row of selectedRows.value) {
          await saveRule({
            id: row.id,
            status: 1,
            pid: row.pid,
            module: row.module,
            title: row.title,
            name: row.name,
            mig_src: row.mig_src || row.src, // 使用mig_src字段
            sort: row.sort,
            menu: row.menu,
            icon: row.icon,
            showLeftMenu: row.showLeftMenu,
          })
        }
        ElMessage.success('批量启用成功')
        addRecentAction(`批量启用了 ${selectedIds.length} 个节点`)
        await getRootNodes()
      } else if (command === 'disable') {
        await ElMessageBox.confirm(`确认禁用选中的 ${selectedIds.length} 个节点吗？`)
        // 批量禁用逻辑
        for (const row of selectedRows.value) {
          await saveRule({
            id: row.id,
            status: 0,
            pid: row.pid,
            module: row.module,
            title: row.title,
            name: row.name,
            mig_src: row.mig_src || row.src, // 使用mig_src字段
            sort: row.sort,
            menu: row.menu,
            icon: row.icon,
            showLeftMenu: row.showLeftMenu,
          })
        }
        ElMessage.success('批量禁用成功')
        addRecentAction(`批量禁用了 ${selectedIds.length} 个节点`)
        await getRootNodes()
      } else if (command === 'delete') {
        await ElMessageBox.confirm(
          `确认删除选中的 ${selectedIds.length} 个节点吗？删除后无法恢复！`,
          '警告',
          {
            confirmButtonText: '确认删除',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )
        // 批量删除逻辑
        for (const row of selectedRows.value) {
          await deleteRule({ id: row.id })
        }
        ElMessage.success('批量删除成功')
        addRecentAction(`批量删除了 ${selectedIds.length} 个节点`)
        await getRootNodes()
      }
    } catch (error) {
      // 用户取消或操作失败
    }
  }

  // 状态切换
  const handleStatusChange = async (row: any, newStatus: number) => {
    try {
      await saveRule({
        id: row.id,
        status: newStatus,
        pid: row.pid,
        module: row.module,
        title: row.title,
        name: row.name,
        mig_src: row.mig_src || row.src, // 使用mig_src字段
        sort: row.sort,
        menu: row.menu,
        icon: row.icon,
        showLeftMenu: row.showLeftMenu,
      })
      ElMessage.success(newStatus === 1 ? '已启用' : '已禁用')
      addRecentAction(`${newStatus === 1 ? '启用' : '禁用'}了节点：${row.title}`)
    } catch (error) {
      row.status = newStatus === 1 ? 0 : 1
      ElMessage.error('操作失败')
    }
  }

  // 添加最近操作
  const addRecentAction = (text: string) => {
    recentActions.value.unshift({
      id: Date.now(),
      text,
    })
    if (recentActions.value.length > 5) {
      recentActions.value.pop()
    }
  }

  // 操作点击处理
  const handleActionClick = (action: any) => {
    console.log('执行最近操作:', action)
  }

  // 处理父级变更
  const handleParentChange = (value: any) => {
    ruleForm.pid = value
  }

  // 查看规则详情
  const handleView = (row: any) => {
    currentViewRow.value = row
    viewDrawerVisible.value = true
  }

  // 添加子菜单
  const handleAddChild = async (row: any) => {
    isEdit.value = false
    drawerTitle.value = '添加子菜单/节点'
    ruleForm.id = 0
    ruleForm.pid = row.id

    // 直接使用英文模块名，不需要转换
    ruleForm.module = row.module || ''

    ruleForm.title = ''
    ruleForm.name = ''
    ruleForm.src = ''
    ruleForm.status = 1
    ruleForm.condition = ''
    ruleForm.listorder = 0
    ruleForm.desc = ''
    ruleForm.sort = 0
    ruleForm.menu = 1
    ruleForm.icon = ''
    ruleForm.showLeftMenu = 1

    await Promise.all([loadAllNodesForDropdown()])

    drawerVisible.value = true
  }

  // 处理添加
  const handleAdd = async (row: any = {}) => {
    isEdit.value = false
    drawerTitle.value = '添加根节点'
    ruleForm.id = 0
    ruleForm.pid = row.id || 0
    ruleForm.module = ''
    ruleForm.title = ''
    ruleForm.name = ''
    ruleForm.src = ''
    ruleForm.status = 1
    ruleForm.condition = ''
    ruleForm.listorder = 0
    ruleForm.desc = ''
    ruleForm.sort = 0
    ruleForm.menu = 1
    ruleForm.icon = ''
    ruleForm.showLeftMenu = 1

    await Promise.all([loadAllNodesForDropdown()])

    drawerVisible.value = true
  }

  // 处理编辑
  const handleEdit = async (row: any) => {
    isEdit.value = true
    drawerTitle.value = '编辑节点'
    ruleForm.id = row.id
    ruleForm.pid = row.pid
    // 直接使用英文模块名，不需要转换
    ruleForm.module = row.module || ''
    ruleForm.title = row.title
    ruleForm.name = row.name
    ruleForm.src = row.src
    ruleForm.status = row.status
    ruleForm.condition = row.condition
    ruleForm.listorder = row.listorder
    ruleForm.desc = row.desc
    ruleForm.sort = row.sort || 0
    ruleForm.menu = row.menu || 1
    ruleForm.icon = row.icon || ''
    ruleForm.showLeftMenu = row.showLeftMenu !== undefined ? row.showLeftMenu : 1

    await Promise.all([loadAllNodesForDropdown()])

    drawerVisible.value = true
  }

  // 删除规则
  const handleDelete = async (row: any) => {
    ElMessageBox.confirm(`确认删除节点【${row.title}】吗？`, '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(async () => {
        try {
          const loadingInstance = ElLoading.service({ text: '删除中...' })

          const response: any = await deleteRule({ id: row.id })

          ElMessage.success('删除成功')
          addRecentAction(`删除了节点：${row.title}`)

          if (row.pid === 0) {
            await getRootNodes()
          } else {
            const parentNode = ruleList.value.find(item => item.id === row.pid)
            if (parentNode) {
              parentNode.hasChildren = true
            }
            await getRootNodes()
          }
        } catch (error) {
          ElMessage.error('删除失败')
        } finally {
          ElLoading.service().close()
        }
      })
      .catch(() => {
        // 用户取消删除
      })
  }

  // 提交规则
  const submitRule = async () => {
    if (!ruleFormRef.value) return

    try {
      // 直接使用表单中的模块名（下拉框value已经是英文名）
      const moduleName = ruleForm.module

      await ruleFormRef.value.validate()

      const params = {
        id: ruleForm.id,
        pid: ruleForm.pid,
        module: moduleName,
        title: ruleForm.title,
        name: ruleForm.name,
        mig_src: ruleForm.src, // 提交mig_src字段，而不是src
        status: ruleForm.status,
        condition: ruleForm.condition,
        listorder: ruleForm.listorder,
        desc: ruleForm.desc,
        sort: ruleForm.sort,
        menu: ruleForm.menu,
        icon: ruleForm.icon,
        showLeftMenu: ruleForm.showLeftMenu,
      }

      const loadingInstance = ElLoading.service({ text: '保存中...' })

      await saveRule(params)

      ElMessage.success(isEdit.value ? '编辑成功' : '添加成功')
      addRecentAction(`${isEdit.value ? '编辑' : '添加'}了节点：${ruleForm.title}`)
      drawerVisible.value = false

      if (ruleForm.pid === 0 || (isEdit.value && ruleForm.pid === 0)) {
        await getRootNodes()
      } else {
        const parentNode = ruleList.value.find(item => item.id === ruleForm.pid)
        if (parentNode) {
          parentNode.hasChildren = true
        }
        await getRootNodes()
      }
    } catch (error) {
      ElMessage.error(isEdit.value ? '编辑失败' : '添加失败')
    } finally {
      ElLoading.service().close()
    }
  }

  // 关闭抽屉
  const handleDrawerClose = () => {
    if (ruleFormRef.value) {
      ruleFormRef.value.resetFields()
    }
  }

  // 添加行样式类名方法
  const getRowClassName = ({ row }: { row: any }) => {
    if (!row) return ''

    const level = row._level !== undefined ? row._level : 0
    return `level-${level}-row`
  }

  // 添加单元格样式类名方法
  const getCellClassName = ({ row, column }: { row: any; column: any }) => {
    if (!row || column.property !== 'title') return ''

    const level = row._level !== undefined ? row._level : 0
    return `level-${level}-cell`
  }

  // 获取模块颜色
  const getModuleColor = (moduleName: string) => {
    const colors: Record<string, string> = {
      home: '#1677ff',
      user: '#52c41a',
      oa: '#fa8c16',
      crm: '#eb2f96',
    }
    return colors[moduleName] || '#8c8c8c'
  }

  // 组件挂载时获取数据
  onMounted(() => {
    getRootNodes()
  })
</script>

<style scoped>
  .rule-management-optimized {
    padding: 20px;
    background: #f5f5f5;
    min-height: 100vh;
  }

  /* 颜色变量 */
  :root {
    --level-0-color: #409eff;
    --level-1-color: #67c23a;
    --level-2-color: #e6a23c;
    --level-3-color: #f56c6c;
    --level-4-color: #909399;

    --level-0-bg: #f0f7ff;
    --level-1-bg: #f6fbff;
    --level-2-bg: #fafdff;
    --level-3-bg: #fff9f9;
    --level-4-bg: #fafafa;

    --shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.1);
    --shadow-md: 0 4px 8px rgba(0, 0, 0, 0.12);
  }

  /* 搜索过滤栏 */
  .search-filter-card {
    margin-bottom: 20px;
  }

  .search-filter-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 16px;
  }

  .search-group {
    display: flex;
    gap: 12px;
    flex-wrap: wrap;
  }

  .action-group {
    display: flex;
    gap: 8px;
  }

  /* 统计容器 */
  .stats-container {
    margin-bottom: 20px;
  }

  /* 统计卡片 */
  .stats-cards {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 16px;
  }

  .stat-card {
    border-radius: 8px;
    transition: all 0.3s;
    border: none;
    box-shadow: var(--shadow-sm);
  }

  .stat-card:hover {
    box-shadow: var(--shadow-md);
    transform: translateY(-2px);
  }

  .stat-content {
    display: flex;
    align-items: center;
    gap: 16px;
  }

  .stat-icon {
    width: 56px;
    height: 56px;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 24px;
  }

  .stat-value {
    font-size: 28px;
    font-weight: 700;
    color: #262626;
    line-height: 1;
  }

  .stat-label {
    font-size: 13px;
    color: #8c8c8c;
    margin-top: 4px;
  }

  /* 骨架屏样式 - 优化CLS */
  .stat-skeleton {
    display: flex;
    align-items: center;
    gap: 16px;
  }

  .skeleton-icon {
    width: 56px;
    height: 56px;
    border-radius: 10px;
    background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 37%, #f0f0f0 63%);
    background-size: 400% 100%;
    animation: skeleton-loading 1.4s ease infinite;
  }

  .skeleton-text {
    flex: 1;
  }

  .skeleton-value {
    width: 60px;
    height: 32px;
    background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 37%, #f0f0f0 63%);
    background-size: 400% 100%;
    animation: skeleton-loading 1.4s ease infinite;
    border-radius: 4px;
    margin-bottom: 8px;
  }

  .skeleton-label {
    width: 80px;
    height: 16px;
    background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 37%, #f0f0f0 63%);
    background-size: 400% 100%;
    animation: skeleton-loading 1.4s ease infinite;
    border-radius: 4px;
  }

  @keyframes skeleton-loading {
    0% {
      background-position: 100% 50%;
    }
    100% {
      background-position: 0 50%;
    }
  }

  /* 表格卡片 */
  .table-card {
    border-radius: 8px;
  }

  /* 表格容器 - 优化CLS：添加最小高度 */
  .table-container {
    min-height: 400px;
    position: relative;
    transition: all 0.3s ease;
  }

  /* 表格样式优化 */
  :deep(.rule-tree-table) {
    width: 100%;
  }

  :deep(.rule-tree-table .el-table__body-wrapper) {
    overflow-x: auto;
    transition: all 0.3s ease;
  }

  :deep(.rule-tree-table .el-table__row) {
    transition: all 0.3s ease;
  }

  :deep(.rule-tree-table .el-table__row td) {
    padding: 12px 16px;
    height: 56px; /* 固定行高，避免高度变化 */
    line-height: 1.5;
  }

  /* 表格行悬停效果 */
  :deep(.rule-tree-table .el-table__row:hover td) {
    background-color: #f5f7fa !important;
    transition: background-color 0.2s ease;
  }

  /* 空状态样式 */
  .empty-state {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 200px;
    padding: 40px 0;
  }

  /* 表格展开动画 */
  :deep(.el-table__expand-icon) {
    transition: transform 0.3s ease;
  }

  :deep(.el-table__expand-icon--expanded) {
    transform: rotate(90deg);
    transition: transform 0.3s ease;
  }

  /* 骨架屏行 - 优化CLS：固定高度和动画 */
  .skeleton-rows {
    padding: 0;
  }

  .skeleton-row {
    display: grid;
    grid-template-columns: 55px 280px 100px 120px 180px 150px 100px 100px 220px;
    gap: 0;
    height: 56px; /* 固定高度，与表格行一致 */
    padding: 12px 16px;
    border-bottom: 1px solid #f0f0f0;
    align-items: center;
    transition: all 0.3s ease;
  }

  .skeleton-cell {
    padding: 0 8px;
  }

  .skeleton-bar {
    background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 37%, #f0f0f0 63%);
    background-size: 400% 100%;
    animation: skeleton-loading 1.4s ease infinite;
    border-radius: 4px;
    height: 16px;
  }

  @keyframes skeleton-loading {
    0% {
      background-position: 100% 50%;
    }
    100% {
      background-position: 0 50%;
    }
  }

  /* 节点单元格 */
  .node-cell {
    display: flex;
    align-items: center;
    min-height: 52px;
    transition: all 0.2s;
  }

  .node-cell:hover {
    background-color: #fafafa;
    border-radius: 6px;
    padding: 4px 8px;
  }

  /* 层级图标 */
  .level-icon {
    width: 28px;
    height: 28px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 6px;
    margin-right: 12px;
    font-size: 16px;
    flex-shrink: 0;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  }

  .level-icon-0 {
    background: #1677ff;
    color: white;
  }
  .level-icon-1 {
    background: #52c41a;
    color: white;
  }
  .level-icon-2 {
    background: #fa8c16;
    color: white;
  }
  .level-icon-3 {
    background: #eb2f96;
    color: white;
  }
  .level-icon-4 {
    background: #722ed1;
    color: white;
  }

  /* 节点信息 */
  .node-info {
    flex: 1;
    min-width: 0;
  }

  .node-title {
    display: flex;
    align-items: center;
    gap: 8px;
    font-weight: 500;
    font-size: 14px;
    color: #262626;
  }

  .node-subtitle {
    font-size: 12px;
    color: #8c8c8c;
    margin-top: 2px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  /* 操作组 */
  .operation-group {
    display: flex;
    gap: 4px;
  }

  /* URL 文本 */
  .url-text {
    font-family: 'Monaco', 'Menlo', 'Consolas', monospace;
    font-size: 12px;
    color: #1677ff;
    background: #e6f4ff;
    padding: 2px 6px;
    border-radius: 3px;
  }

  .no-url {
    color: #d9d9d9;
    font-style: italic;
  }

  /* 最近操作 */
  .quick-actions-card {
    margin-top: 20px;
  }

  .recent-actions {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
  }

  .action-tag {
    cursor: pointer;
    transition: all 0.2s;
  }

  .action-tag:hover {
    transform: translateY(-1px);
    box-shadow: var(--shadow-sm);
  }

  /* 抽屉底部 */
  .drawer-footer {
    display: flex;
    justify-content: flex-end;
    padding: 20px;
    border-top: 1px solid #f0f0f0;
    gap: 12px;
  }

  /* 抽屉底部按钮 */
  .drawer-footer .el-button {
    margin-left: 0;
  }

  /* 颜色样式 */
  .red {
    color: #f56c6c;
  }

  .green {
    color: #67c23a;
  }

  /* 层级样式增强 */
  :deep(.el-table__body .level-0-row) {
    background-color: var(--level-0-bg) !important;
    font-weight: bold !important;
  }

  :deep(.el-table__body .level-0-row .level-0-cell) {
    border-left: 4px solid var(--level-0-color) !important;
    padding-left: 24px !important;
  }

  :deep(.el-table__body .level-1-row) {
    background-color: var(--level-1-bg) !important;
  }

  :deep(.el-table__body .level-1-row .level-1-cell) {
    border-left: 4px solid var(--level-1-color) !important;
    padding-left: 24px !important;
  }

  :deep(.el-table__body .level-2-row) {
    background-color: var(--level-2-bg) !important;
  }

  :deep(.el-table__body .level-2-row .level-2-cell) {
    border-left: 4px solid var(--level-2-color) !important;
    padding-left: 24px !important;
  }

  :deep(.el-table__body .level-3-row) {
    background-color: var(--level-3-bg) !important;
  }

  :deep(.el-table__body .level-3-row .level-3-cell) {
    border-left: 4px solid var(--level-3-color) !important;
    padding-left: 24px !important;
  }

  :deep(.el-table__body .level-4-row),
  :deep(.el-table__body .level-5-row),
  :deep(.el-table__body .level-6-row) {
    background-color: var(--level-4-bg) !important;
  }

  :deep(.el-table__body .level-4-row .level-4-cell),
  :deep(.el-table__body .level-5-row .level-5-cell),
  :deep(.el-table__body .level-6-row .level-6-cell) {
    border-left: 4px solid var(--level-4-color) !important;
    padding-left: 24px !important;
  }

  /* 表格行悬停效果 */
  :deep(.el-table__row:hover td) {
    background-color: #ebf5ff !important;
  }

  /* 树形图标优化 */
  :deep(.el-table__expand-icon) {
    margin-right: 4px !important;
    font-size: 16px !important;
    display: inline-flex !important;
    align-items: center !important;
    justify-content: center !important;
    width: 20px !important;
    height: 20px !important;
  }

  :deep(.el-table__expand-icon .el-icon) {
    font-size: 16px !important;
    transition: transform 0.2s ease !important;
    color: #666 !important;
  }

  :deep(.el-table__expand-icon--expanded .el-icon) {
    transform: rotate(90deg) !important;
  }

  /* 确保有子节点的行总是显示展开图标 */
  :deep(.el-table__body .el-table__row.has-children .el-table__expand-icon) {
    display: inline-flex !important;
    visibility: visible !important;
    opacity: 1 !important;
  }

  /* 优化表格行高和间距 */
  :deep(.el-table__row) {
    transition: all 0.2s ease;
  }

  :deep(.el-table__body td) {
    padding: 10px 12px;
  }

  /* 响应式设计 */
  @media (max-width: 1200px) {
    .search-group {
      flex-direction: column;
      align-items: stretch;
    }

    .search-group .el-input,
    .search-group .el-select {
      width: 100% !important;
    }

    .action-group {
      flex-wrap: wrap;
    }
  }

  @media (max-width: 768px) {
    .rule-management-optimized {
      padding: 12px;
    }

    .stats-cards {
      grid-template-columns: repeat(2, 1fr);
    }

    .stat-icon {
      width: 48px;
      height: 48px;
      font-size: 20px;
    }

    .stat-value {
      font-size: 24px;
    }

    .operation-group {
      flex-direction: column;
    }
  }
</style>
